package com.tenton.routing;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @ClassName: RoutingTopicConsumer2
 * @Description： 4、路由订阅模式 消费者2 通配符 #
 * @Author： tangdong
 * @Date： 2023/12/18
 */
public class RoutingTopicConsumer2 {
    public static void main(String[] args) {
        //1、创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        //设置IP
        connectionFactory.setHost("192.168.1.91");
        //设置端口
        connectionFactory.setPort(15672);
        //设置用户名
        connectionFactory.setUsername("td");
        //设置密码
        connectionFactory.setPassword("123456");
        //设置虚拟主机
        connectionFactory.setVirtualHost("/rabbit-routing");
        Connection connection = null;
        Channel channel = null;
        try {
            //2、创建连接
            connection = connectionFactory.newConnection();
            //3、创建通道
            channel = connection.createChannel();
            //4、声明交换机 参数1:交换机名称 参数2:交换机类型 基于指令的Routing key转发
            channel.exchangeDeclare("topics", "topic");
            //5、创建临时队列
            String queue = channel.queueDeclare().getQueue();
            //6、/绑定队列与交换机并设置获取交换机中动态路由 通配符 #
            channel.queueBind(queue, "topics", "user.#");
            //消费消息
            channel.basicConsume(queue, true, new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    System.out.println("消费者2: " + new String(body));
                }
            });

        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }
}
